//
//  MJ_EditTaskInfoViewController.m
//  UEAssistant
//
//  Created by mac on 2018/2/12.
//  Copyright © 2018年 youyixinxi. All rights reserved.
//

#import "MJ_EditTaskInfoViewController.h"
#import "MJ_EditTaskSingleCell.h"
#import "UITableView+ReisterCell.h"
#import "YHXCalendarView.h"
#import "TagsSecondView.h"
#import "MJ_TagTableViewCell.h"
#import "MJ_SubTitleTableViewCell.h"
#import "MJ_inputTableViewCell.h"
#import "MJ_RemarkTableViewCell.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
@interface MJ_EditTaskInfoViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic)UITableView *tableView;

@property (strong, nonatomic)UIView *coverView;//蒙版

@property (nonatomic, strong) TagsSecondView    *tagsView;//标签选择view

@property (nonatomic, strong) NSMutableArray    *tags;//选中的标签

@property (nonatomic, strong) NSMutableArray    *tagArray;//标签数组

@property (strong, nonatomic)NSMutableDictionary *parameters;

@property (copy, nonatomic)NSString *totalPrice;
@end

@implementation MJ_EditTaskInfoViewController

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height-64) style:UITableViewStylePlain];
        [_tableView registerNibWithClass:[MJ_EditTaskSingleCell class]];
        [_tableView registerNibWithClass:[MJ_TagTableViewCell class]];
        [_tableView registerNibWithClass:[MJ_SubTitleTableViewCell class]];
        [_tableView registerNibWithClass:[MJ_inputTableViewCell class]];
        [_tableView registerNibWithClass:[MJ_RemarkTableViewCell class]];
        _tableView.separatorColor = [UIColor colorWithHexString:@"#e0e0e0"];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}

- (UIView *)coverView{
    
    if (!_coverView) {
        _coverView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, 0)];
        _coverView.backgroundColor = RGB(0, 0, 0, 0.4);
    }
    return _coverView;
}

- (NSMutableDictionary *)parameters {
    if (!_parameters) {
        _parameters = [[NSMutableDictionary alloc] init];
    }
    return _parameters;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"hideCover" object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self initialize];
}
- (void)loadData {
    //获取标签键值对
    _tagArray = [NSMutableArray array];
    [AvailableNetWorking postWithUrl:transLabels_connector params:@{} successHandler:^(id responseObject) {
        
        NSLog(@"tags == %@",responseObject);
        if ([responseObject[@"code"] intValue] == 200) {
            NSArray * arr = responseObject[@"result"];
            [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [_tagArray addObject:obj];
            }];
        }
    } falureHandler:^(NSError *error) {
        
    }];
}

- (void)initialize {
    
    _totalPrice = @"￥0";
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *publishButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [publishButton setTitle:@"发布" forState:UIControlStateNormal];
    publishButton.layer.cornerRadius = 2.0;
    publishButton.layer.masksToBounds = YES;
    publishButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    publishButton.layer.borderWidth = 0.5;
    publishButton.backgroundColor = [UIColor colorWithHexString:@"#F3F4F6"];
    [publishButton setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
    publishButton.titleLabel.font = [UIFont systemFontOfSize:15];
    publishButton.frame = CGRectMake(0, 0, 45, 27);
    [publishButton addTarget:self action:@selector(pulishTaskPressed:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:publishButton];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[[UIImage imageNamed:@"Nav_返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    self.navigationItem.title = @"填写任务信息";

    [self.view addSubview:self.tableView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hideCoverCliced:) name:@"hideCover" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dismissTagsViewRespond) name:@"dismissTagsView" object:nil];

    _tags = [NSMutableArray array];
    _tagsView = [[TagsSecondView alloc]initWithFrame:CGRectMake(0, Screen_Height, Screen_Width, 0)];
    __weak typeof(_tags) weakTags = _tags;
    _tagsView.didSelectSectionHandler = ^(NSString *tag){
        if ([tag isEqualToString:@"重置"]) {
            [weakTags removeAllObjects];
        }
        if (![weakTags containsObject:tag] && ![tag isEqualToString:@"重置"]) {
            [weakTags addObject:[NSString stringWithFormat:@"  %@",tag]];
        }
    };
    [self.view addSubview:_tagsView];
    [self.view addSubview:self.coverView];

}


#pragma mark -- UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            MJ_EditTaskSingleCell *deadTimeCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MJ_EditTaskSingleCell class]) forIndexPath:indexPath];
            __weak typeof(self) weakSelf = self;
            deadTimeCell.deadTimeClick = ^{
                __strong typeof(weakSelf) sSelf = weakSelf;
                [sSelf showCalendar];//显示日历
            };
            return deadTimeCell;
        }
        MJ_TagTableViewCell *tagCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MJ_TagTableViewCell class]) forIndexPath:indexPath];
        return tagCell;

    }else if(indexPath.section == 1){
        
        MJ_SubTitleTableViewCell *subTitleCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MJ_SubTitleTableViewCell class]) forIndexPath:indexPath];
        subTitleCell.contentLabel.textColor = [UIColor colorWithHexString:@"#0d1a26"];
        subTitleCell.contentLabel.font = [UIFont systemFontOfSize:15];
        if (indexPath.row == 0) {
            subTitleCell.titleLabel.text = @"翻译类型";
            subTitleCell.contentLabel.text = self.translateType;
        }else{
            subTitleCell.titleLabel.text = @"任务字数";
            subTitleCell.contentLabel.text = self.wordcount;
        }
        return subTitleCell;
        
    }else if (indexPath.section == 2) {
        
        if (indexPath.row == 0) {
            MJ_inputTableViewCell *inputCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MJ_inputTableViewCell class]) forIndexPath:indexPath];
            inputCell.titleLabel.text = @"单价（元/千字）";
            inputCell.inputTextFiled.placeholder = @"填写单价";
            [inputCell.inputTextFiled addTarget:self action:@selector(editPriceChanged:) forControlEvents:UIControlEventEditingDidEnd];
            return inputCell;
        }else{
            MJ_SubTitleTableViewCell *subTitleCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MJ_SubTitleTableViewCell class]) forIndexPath:indexPath];
            subTitleCell.titleLabel.text = @"总计费用";
            subTitleCell.contentLabel.textColor = [UIColor colorWithHexString:@"#ff6f4c"];
            subTitleCell.contentLabel.font = [UIFont boldSystemFontOfSize:18];
            subTitleCell.contentLabel.text = _totalPrice;
            return subTitleCell;
        }

    }else{
        if (indexPath.row == 0) {
            MJ_inputTableViewCell *inputCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MJ_inputTableViewCell class]) forIndexPath:indexPath];
            inputCell.titleLabel.text = @"取消时间";
            inputCell.inputTextFiled.placeholder = @"填写时间（分钟）";
            [inputCell.inputTextFiled addTarget:self action:@selector(editTime) forControlEvents:UIControlEventEditingChanged];
            return inputCell;
        }
        MJ_RemarkTableViewCell *remark = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MJ_RemarkTableViewCell class]) forIndexPath:indexPath];
        
        return remark;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 1 && indexPath.section == 0) {
        return 80;
    }else if (indexPath.row == 1 && indexPath.section == 3) {
        return 200;
    }
    return 60;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 3) {
        return nil;
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, tableView.sectionFooterHeight)];
    view.backgroundColor = [UIColor colorWithHexString:@"#eeeeee"];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 3) {
        return 0;
    }
    return 15;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 1) {
        [UIView animateWithDuration:0.3 animations:^{
    
            CGRect frame = CGRectMake(0, 61, Screen_Width, Screen_Height-125);
            _tagsView.frame = frame;
            self.coverView.frame = CGRectMake(0, 0, Screen_Width, 61);
            
        } completion:^(BOOL finished) {
    
        }];
        
    }
}

- (void)editPriceChanged:(UITextField *)sender {
    NSString *text = sender.text;
    CGFloat price = text.floatValue/1000.0*self.wordcount.floatValue;
    CGFloat roundPrice = [self roundFloat:price];
    _totalPrice = [NSString stringWithFormat:@"%.2f",roundPrice];
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:2]] withRowAnimation:UITableViewRowAnimationNone];
}
-(float)roundFloat:(float)price{
    return (floorf(price*100 + 0.5))/100;
}
- (void)editTime {
    
}

- (void)showCalendar {
    for (UIView *subView in self.view.subviews) {
        if ([subView isKindOfClass:[YHXCalendarView class]]) {
            [subView removeFromSuperview];
        }
    }
    YHXCalendarView *view = [[YHXCalendarView alloc]initWithFrame:CGRectMake(0, Screen_Height, Screen_Width, 0)];
    [self.view addSubview:view];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        CGRect frame = CGRectMake(0, 61, Screen_Width, Screen_Height-125);
        view.frame = frame;
        self.coverView.frame = CGRectMake(0, 0, Screen_Width, 61);
        
    } completion:^(BOOL finished) {
        
    }];
}


- (void)hideCoverCliced:(NSNotification *)notification{
    
    NSLog(@"notification.object --- %@",notification.object);
    MJ_EditTaskSingleCell *deadCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    deadCell.deadTimeString = [NSString stringWithFormat:@"%@",notification.object];
    self.parameters[@"deadlineTime"] = [NSString stringWithFormat:@"%@",notification.object];
    [UIView animateWithDuration:0.3 animations:^{
        
        self.coverView.frame = CGRectMake(0, 0, Screen_Width, 0);
        
    } completion:^(BOOL finished) {
        
    }];
}
- (void)dismissTagsViewRespond{
    
    for (NSString *str in _tags) {
        NSLog(@"tag ===== %@",str);
    }
    NSSet *set = [NSSet setWithArray:_tags];
    [_tags removeAllObjects];
    for (NSString *str in set) {
        [_tags addObject:str];
    }
    
    //获取标签组
    NSMutableArray *endTags = [NSMutableArray array];
    [_tagArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        for (NSString *tag in _tags) {
            if ([tag isEqualToString:[NSString stringWithFormat:@"  %@",obj[@"labelName"]]]) {
               [endTags addObject:[NSString stringWithFormat:@"%@_%@",obj[@"labelId"],obj[@"labelName"]]];
            }
        }
    }];
    NSString *labelStr = [endTags componentsJoinedByString:@","];
    NSLog(@"endStr = %@",labelStr);
    
    self.parameters[@"labelIdnameList"] = labelStr;
    
    MJ_TagTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    cell.selectedTagsList = _tags;
    
    [UIView animateWithDuration:0.25 animations:^{
        
        CGRect frame = CGRectMake(0, Screen_Height, Screen_Width, 0);
        _tagsView.frame = frame;
        self.coverView.frame = CGRectMake(0, 0, Screen_Width, 0);
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)pulishTaskPressed:(UIButton *)sender {
    //备注
    MJ_RemarkTableViewCell *momo = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:3]];
    self.parameters[@"momo"] = momo.momoTextView.text;
    //分钟数
    MJ_inputTableViewCell *input = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:3]];
    self.parameters[@"publishEndAfterTime"] = input.inputTextFiled.text;
    //单价
    MJ_inputTableViewCell *price = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    self.parameters[@"price"] = price.inputTextFiled.text;
    
    self.parameters[@"projectId"] = detailsModel.product_Id;
    self.parameters[@"sourcelangkey"] = detailsModel.sourceKey;
    self.parameters[@"targetlangkey"] = detailsModel.targetlangkey;
    self.parameters[@"vmPhone"] = shareData.phone;
    self.parameters[@"sectorId"] = self.sectorId;
    self.parameters[@"docId"] = self.docId;
    self.parameters[@"endRownum"] = self.endRownum;
    self.parameters[@"resultcount"] = @"";//后端废弃参数
    self.parameters[@"needTrail"] = @"0";//需不需要试译
    self.parameters[@"trailContent"] = @"";//试译内容
    self.parameters[@"trailEndtime"] = @"";//试译截止时间

    
    //发布任务
    [AvailableNetWorking postWithUrl:@"/enterprise/task/plattaskPublish" params:self.parameters successHandler:^(id responseObject) {
        if ([responseObject[@"code"] integerValue] == 200) {
            
        }else{
            [TopAlertView SetUpbackgroundColor:[UIColor redColor] andStayTime:1.5 andImageName:@"" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:YES];
        }
        NSLog(@"%@",responseObject);
        
    } falureHandler:^(NSError *error) {
        
    }];
    
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
